package com.omniseckill.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.omniseckill.dto.UserDTO;
import com.omniseckill.entity.User;
import com.omniseckill.service.IUserService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;


import javax.annotation.Resource;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class GetTokensAndWriteFiles {
    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Test
    void getTokensAndWriteFiles() throws IOException{
        List<User> users=userService.lambdaQuery().last("limit 1000").list();
        FileWriter fileWriter=null;
        try {
            fileWriter=new FileWriter("D:\\黑马redis学习资料\\02-实战篇\\资料\\tokens.txt");//文件位置
            for(User user:users){
                //1.保存用户信息到 Redis中
                //1.1 随机生成token作为登录令牌
                String token= UUID.randomUUID().toString(true);
                //1.2 将user对象转化为hashmap存储
                UserDTO userDTO= BeanUtil.copyProperties(user,UserDTO.class);
                Map<String,Object> userMap=BeanUtil.beanToMap(userDTO,new HashMap<>(),
                        CopyOptions.create()
                                .setIgnoreNullValue(true)
                                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
                //1.3 存储
                String tokenKey=RedisConstants.LOGIN_USER_KEY+token;
                stringRedisTemplate.opsForHash().putAll(tokenKey,userMap);
                //1.4 设置token有效期
                stringRedisTemplate.expire(tokenKey,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);

                //将 Redis中的 token写入文件中
                fileWriter.append(token);
                fileWriter.append("\n");
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }finally {
            fileWriter.close();
        }
    }
}
